package ilincar.systemcore.net;

import android.content.Context;
import android.os.AsyncTask;
import android.provider.Settings;
import android.text.TextUtils;

import com.ilincar.utils.IlincarUrls;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import ilincar.systemcore.tool.ILog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by ilincar on 2016/12/9.
 */

public class IlincarRequest {

    private final String TAG = "IlincarRequest";
    private Context mContext = null;
    private String mMacAddress = null;

    private final int TIME_OUT = 20;
    private int mCurrentTimeCnt = 0;
    private final int MAX_TIME_OUT_CNT = 3;
    //private final OkHttpClient mOkHttpClient = new OkHttpClient();
    private final OkHttpClient mOkHttpClient = new OkHttpClient.Builder().connectTimeout(TIME_OUT,
            TimeUnit.SECONDS).readTimeout(TIME_OUT, TimeUnit.SECONDS).build();

    public IlincarRequest(Context context) {
        this.mContext = context;
        macNullIf();
    }

    private void macNullIf() {
        if (TextUtils.isEmpty(mMacAddress)) {
            mMacAddress = IlincarUtils.getIntMacByShell();
            if (TextUtils.isEmpty(mMacAddress))
                mMacAddress = Settings.System.getString(mContext.getContentResolver(), "mac_addr");
        }
    }

    private RequestBody getRequestBody(Map<String, String> bodyParams) {
        RequestBody requestBody = null;
        FormBody.Builder builder = new FormBody.Builder();
        if (bodyParams != null) {
            for (Map.Entry<String, String> entry : bodyParams.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }

        requestBody = builder.build();
        return requestBody;
    }

    public interface RequestCallBack {
        void onFailure(IOException e);

        void onResponse(String result);
    }

    /**
     * 单个请求，没有表单,没有加密
     */
    public void postToServer(String url, final RequestCallBack callback) {
        final Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if((e.getCause() != null) && e.getCause().equals(SocketTimeoutException.class) && (mCurrentTimeCnt < MAX_TIME_OUT_CNT)) {
                    mOkHttpClient.newCall(call.request()).enqueue(this);
                }else{
                    if (callback != null)
                        callback.onFailure(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    if (callback != null)
                        callback.onResponse(response.body().string());
                }
            }
        });
    }


    /**
     * 提交表单
     */
    public void postToServer(String url, JSONObject jsonObject, final RequestCallBack callback) {
        try {
            Request request = null;
            macNullIf();
            if (jsonObject != null) {
                String jsondata = jsonObject.toString();
                FormBody formBody = new FormBody.Builder().add("jsondata", jsondata).build();
                request = new Request.Builder().url(url)
                        .header("appVer", "10")
                        .addHeader("clientId", mMacAddress)
                        .addHeader("os", "android_c")
                        .post(formBody)
                        .build();
            } else {
                request = new Request.Builder().url(url)
                        .header("appVer", "10")
                        .addHeader("clientId", mMacAddress)
                        .addHeader("os", "android_c")
                        .build();
            }

            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if((e.getCause() != null) && e.getCause().equals(SocketTimeoutException.class) && (mCurrentTimeCnt < MAX_TIME_OUT_CNT)) {
                        mOkHttpClient.newCall(call.request()).enqueue(this);
                    } else if (callback != null) {
                        callback.onFailure(e);
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String result = IlincarUtils.getEncodeAndGzip(response.body().string());
                        if (callback != null)
                            callback.onResponse(result);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 提交表单
     *
     * @param url
     * @param bodyParams
     * @param callback
     */
    public void postToServer(String url, Map<String, String> bodyParams, final RequestCallBack callback) {

        macNullIf();
        Request request = new Request.Builder().url(url)
                .header("appVer", "10")
                .addHeader("clientId", mMacAddress)
                .addHeader("os", "android_c")
                .post(getRequestBody(bodyParams))
                .build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if((e.getCause() != null) && e.getCause().equals(SocketTimeoutException.class) && (mCurrentTimeCnt < MAX_TIME_OUT_CNT)) {
                    mOkHttpClient.newCall(call.request()).enqueue(this);
                }else if (callback != null){
                    callback.onFailure(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = IlincarUtils.getEncodeAndGzip(response.body().string());
                    if (callback != null)
                        callback.onResponse(result);
                }
            }
        });
    }

    /**
     * 上传
     *
     * @param url
     * @param bodyParams 上传文件，　头，和文件　目前文件分为file rt_video
     * @param callback
     */
    public void uploadFile(String url, HashMap<String, Object> bodyParams, final RequestCallBack callback) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        if (bodyParams != null) {
            for (String key : bodyParams.keySet()) {
                Object object = bodyParams.get(key);
                if (object instanceof File) {
                    //如果是文件
                    File file = (File) object;
                    //builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(null, file));
                } else {
                    builder.addFormDataPart(key, object.toString());
                }
            }
        }
        macNullIf();
        RequestBody body = builder.build();
        Request request = new Request.Builder().url(url)
                .header("appVer", "10")
                .addHeader("clientId", mMacAddress)
                .addHeader("deviceId", mMacAddress)
                .addHeader("os", "android_c")
                .post(body)
                .build();

        mCurrentTimeCnt = 0;
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if((e.getCause() != null) && e.getCause().equals(SocketTimeoutException.class) && (mCurrentTimeCnt < MAX_TIME_OUT_CNT)) {
                    mOkHttpClient.newCall(call.request()).enqueue(this);
                }else if (callback != null) {
                    callback.onFailure(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = IlincarUtils.getEncodeAndGzip(response.body().string());
                    if (callback != null)
                        callback.onResponse(result);
                }
            }
        });
    }

    /**
     * 下载语言件
     *
     * @param url      下载地址
     * @param callback 下载回调
     */
    public void downloadFile(String url, final RequestCallBack callback) {
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if((e.getCause() != null) && e.getCause().equals(SocketTimeoutException.class) && (mCurrentTimeCnt < MAX_TIME_OUT_CNT)) {
                    mOkHttpClient.newCall(call.request()).enqueue(this);
                }else if (callback != null){
                    callback.onFailure(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = IlincarUtils.getEncodeAndGzip(response.body().string());
                    if (callback != null)
                        callback.onResponse(result);
                }
            }
        });
    }

    /**
     * 提交表单
     */
    public void sendPushId() {
        try {
            Request request = null;
            macNullIf();
            StringBuilder jsondata = new StringBuilder("{");
            jsondata.append("\"pushId\":\"").append(mMacAddress).append("\"")
                    .append(",\"clientId\":\"").append(mMacAddress).append("\"")
                    .append(",\"clientType\":2")
                    .append("}");
            FormBody formBody = new FormBody.Builder().add("jsondata", jsondata.toString()).build();
            request = new Request.Builder().url(IlincarUrls.DDPUSH_ID_UPLOAD_URL)
                    .header("appVer", "10")
                    .addHeader("clientId", mMacAddress)
                    .addHeader("os", "android_c")
                    .post(formBody)
                    .build();
            jsondata = null;
            Response response = mOkHttpClient.newCall(request).execute();
            if (response != null && response.isSuccessful()) {
                // access OK
                ILog.d(TAG, "==upload pushId success==!!" + response.body().string());
            }
            else
                ILog.d(TAG, "==upload pushId failed==!!");
        } catch (Exception e) {
            e.printStackTrace();
            ILog.d(TAG, "==upload pushId exception==!!");
        }

    }


}

